package com.charmzenus.smallshop.config.readWriteConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(value = "com.charmzenus.smallshop.repository",
                        entityManagerFactoryRef = "dataEntityManagerFactory",
                        transactionManagerRef="dataTransactionManager")
public class DataSourceConfig {

	@Autowired
    JpaProperties jpaProperties;

    @Autowired
    @Qualifier("routingDataSource")
    private DataSource routingDataSource;

    /**
     * 我们通过LocalContainerEntityManagerFactoryBean来获取EntityManagerFactory实例
     * @return
     */
    @Bean(name = "dataEntityManagerFactoryBean")
    @Primary
    public LocalContainerEntityManagerFactoryBean dataEntityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(routingDataSource)
                .properties(jpaProperties.getProperties())
                .packages("com.charmzenus.smallshop.bean") //设置实体类所在位置
                .persistenceUnit("writePersistenceUnit")
                .build();
        //.getObject();//不要在这里直接获取EntityManagerFactory
    }

    /**
     * EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory
     * 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session,
     * mybatis的sqlSession.
     * @param builder
     * @return
     */
    @Bean(name = "dataEntityManagerFactory")
    public EntityManagerFactory dataEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return this.dataEntityManagerFactoryBean(builder).getObject();
    }

    /**
     * 配置事物管理器
     * @return
     */
    @Bean(name = "dataTransactionManager")
    public PlatformTransactionManager dataTransactionManager(EntityManagerFactoryBuilder builder) {
        // 这里可以使用自定义的事务管理类  =》 MyJpaTransactionManager
        return new JpaTransactionManager(dataEntityManagerFactory(builder));
    }
}